const Controller = require("egg").Controller;

class BlogController extends Controller {
    /**
     * 添加博客
     */
    async create() {
        // 解构参数
        const { title, content } = this.ctx.request.body;
        // 获取当前登录用户id
        const uid = this.ctx.user.id;
        // 非空校验
        if (!title || !content) {
            this.ctx.body = {
                code: 400,
                message: "缺少必须参数",
            };
            return;
        }
        // 保存博客信息到数据库
        const res = await this.service.blog.addBlog(title, content, uid);
        // 判断是否添加成功
        if (res.affectedRows === 1) {
            this.ctx.body = {
                code: 201,
                message: "添加成功",
            };
        } else {
            this.ctx.body = {
                code: 500,
                message: "添加失败",
            };
        }
    }

    /**
     * 博客列表
     */
    async index() {
        const list = await this.service.blog.readList();
        this.ctx.body = {
            code: 200,
            data: {
                list,
            },
            message: "请求列表成功",
        };
    }

    /**
     * 获取博客详情
     */
    async detail() {
        // 解析路径参数
        const { id } = this.ctx.params;
        // 获取详情
        const blog = await this.service.blog.find(id);
        // 返回
        this.ctx.body = {
            code: 200,
            data: blog,
            message: "请求成功",
        };
    }
}

module.exports = BlogController;
